package com.kk.handlers;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kk.common.Result;
import com.kk.common.ResultCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 自定义授权失败处理器
 * 当已认证用户访问无权限资源时触发
 *
 * @author kl
 * @version 1.0
 * @date 2025/10/15
 */
@Slf4j
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {

        log.warn("无权限访问资源: URI={}, 用户={}, 异常={}",
                request.getRequestURI(),
                request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : "unknown",
                accessDeniedException.getMessage());

        // 设置响应状态和内容类型
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 返回统一的错误响应
        Result<Void> result = Result.fail(
                ResultCode.FORBIDDEN.getCode(),
                "权限不足，无法访问该资源"
        );

        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
